<?php

class __users_ajax extends Module {
	
	public function __construct () {
		parent::__construct ('users');
	}
	
	/**
	 * Добавить/удалить указанного пользователя из списка друзей текущего пользователя
	 * @return void
	 */
	public function ajax_set_friend () {
		$this->expectSecureGET();
		
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oFriendType = $typesController->getTypeByName ('friend');
		$oUserType = $typesController->getTypeByName ('user');
		
		$requestUserId = getRequest ('param0', 'int');
		
		$selFriend = new Selection;
		$selFriend->addType ($oFriendType);
		$selFriend->addFilter ('user_id', ExplaySession::getUserId ());
		$selFriend->addFilter ('friend_id', $requestUserId);
		$selFriend->addLimit (1);
		
		if ($selFriend->getTotalCount () == 1) {
			$res = $selFriend->getList ();
			
			$oFriend = $objectsController->getObject ($oFriendType, $res[0][0]);
			$oFriend->delete ();
			
			$oCurrentUser = ExplaySession::getUser ();
			$cntFriends = $oCurrentUser->getValue ('count_friends');
			$oCurrentUser->setValue ('count_friends', --$cntFriends);
			$oCurrentUser->save ();
			
			$this->flush ((string) new Array2XML ('data', array ('result' => '-1')), 'text/xml');
		} else {
			if ($oFriendUser = $objectsController->getObject ($oUserType, $requestUserId)) {			
				$oNewFriend = new Object ($oFriendType);
				$oNewFriend->setValues (array (
					'user_id' => ExplaySession::getUserId (),
					'friend_id' => $requestUserId
				));
				$oNewFriend->createNew ();
				
				// Добавляем запись в лог
				$oLog = new Object ($typesController->getTypeByName ('log_friend'));
				$oLog->setValues (array (
					'date' => time (),
					'user_id' => ExplaySession::getUserId (),
					'added_friend_user_id' => $requestUserId 
				));
				$oLog->createNew ();
				
				$oCurrentUser = ExplaySession::getUser ();
				$cntFriends = $oCurrentUser->getValue ('count_friends');
				$oCurrentUser->setValue ('count_friends', ++$cntFriends);
				$oCurrentUser->save ();
				
				$this->sendMessageToFriend ($oFriendUser);				
				
				$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
			} else {
				$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
			}
		}
	}
	
	/**
	 * Голосовать за указанного пользователя
	 * @return void
	 */
	public function ajax_user_rating () {
		$this->expectSecureGET();
		
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oUserType = $typesController->getTypeByName ('user');
		$oVoteType = $typesController->getTypeByName ('vote');
		
		$userId = getRequest ('param0', 'int');
		$isGood = getRequest ('param1', 'int');
		
		if (!$oUser = $objectsController->getObject ($oUserType, $userId)) {
			$this->flush ((string) new Array2XML ('data', array ('error' => lang ('error_ajax_user_not_exists','users'))), 'text/xml');
		}
		
		$selVoted = new Selection;
		$selVoted->addType ($oVoteType);
		$selVoted->addFilter ('type_id', $oUserType->getId ());
		$selVoted->addFilter ('object_id', $userId);
		$selVoted->addFilter ('user_id', ExplaySession::getUserId());
			
		if (count ($selVoted->getList ()) > 0) {
			 $this->flush ((string) new Array2XML ('data', array ('error' => lang ('error_ajax_already_voted','users'))), 'text/xml');
		}
		
		$rating = (float) $oUser->getValue ('rating');
		$votes = (int) $oUser->getValue ('rating_votes');
		$dRating = (float) ('1.' . mt_rand (0,99));
		if ($isGood == 1) {
			$newRating = $rating + $dRating;
		} else {
			$newRating = $rating - $dRating;
		}
		$oUser->setValue ('rating', (float) $newRating);
		$oUser->setValue ('rating_votes', ++$votes);
		$oUser->save ();
		
		$oVote = new Object ($oVoteType);
		$oVote->setValues (array (
			'type_id' => $oUserType->getId (),
			'object_id' => $userId,
			'user_id' => ExplaySession::getUserId(),
			'mark' => $isGood == 1 ? '1' : '0'
		));
		$oVote->createNew ();
		
		$this->flush ((string) new Array2XML ('data', array ('votes' => $votes, 'rating' => number_format ($newRating, 2, ',', ' '))), 'text/xml');
	}
	
	private function sendMessageToFriend (Object $oUser) {
		$typesController = TypesController::getInstance ();
		
		$oTypeNotif = $typesController->getTypeByName ('system_notification');
		$my = ExplaySession::getUser ();
		
		$oMessage = new Object ($oTypeNotif);		
		
		$template = new SimpleTemplate ('users/friendNotification.tpl');
		$template->setVar ('{name}', $my->getValue ('name'));
		$template->setVar ('{login}', $my->getValue ('login'));
		
		$oMessage->setValues (array (
			'addressed_user_id' => $oUser->getId (),
			'subject' => lang('notification_friends_subject','users'),
			'text' => $template->display (),
			'date' => time ()
		));
		
		$oMessage->createNew ();
		
		$oTypeStatus = $typesController->getTypeByName ('message_status');
				
		$oStatus = new Object ($oTypeStatus);
		$oStatus->setValues (array (
			'message_id' => $oMessage->getId (),
			'type_id' => $oTypeNotif->getId (),
			'user_id' => $oUser->getId (),
			'read' => '0'	
		));
		$oStatus->createNew ();
	}
	
}